package com.logic.saas.action.user;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.validation.SkipValidation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;

import com.logic.saas.action.BaseAction;
import com.logic.saas.dto.RegisterDTO;
import com.logic.saas.enums.SessionKey;
import com.logic.saas.exception.ValidationException;
import com.logic.saas.pojo.Organization;
import com.logic.saas.pojo.Qcode;
import com.logic.saas.pojo.User;
import com.logic.saas.service.QcodeService;
import com.logic.saas.service.security.UserService;
import com.logic.saas.util.AddLog;
/**
 * useraction 
 * 
 * */
public class UserAction  extends BaseAction{

	
	private RegisterDTO registerdto;
	private static final long serialVersionUID = -5313575458153317753L;
	@Autowired
	private UserService userservice;
	@Autowired
	private QcodeService qcodeService;

	@Action(value="register")
	@SkipValidation
    public String execute(){
		AddLog.addToLog(this.getClass(), AddLog.INFO, "forward to register modules page.....");
		
		try {
			//查询State和Country
			List<Qcode> state = qcodeService.getState();
			request.setAttribute("state", state);
			List<Qcode> country = qcodeService.getCountry();
			request.setAttribute("country", country);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		String returnedStr = SUCCESS;
    	return returnedStr;
	}
	
	@Action(value="registerinsert", results={@Result(name="success", type="redirect", location="/login.action")})     
	public String register(){
		String registerSuccess = ERROR;
		String errorMessage= this.getText("error.register_failed");
		Integer userId = (Integer)session.get(SessionKey.USERID);
		if(null != registerdto.getUser()&& null != registerdto.getOrg()){
			try {
				//TODO
				registerdto.getUser().setType(1);
				userservice.register(userId,registerdto);
				registerSuccess = SUCCESS;
			}catch (DataAccessException e) {
				errorMessage = errorMessage + " : " + this.handelDataAccessException(e);
				AddLog.addToLog(this.getClass(), AddLog.ERROR, "Register error"+e.getMessage());
			}catch(ValidationException ve){
				errorMessage = ve.getMessage();
			}catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		if(registerSuccess.equals(ERROR)){
			this.addActionError(errorMessage);
		}
		return registerSuccess;
	}

	public RegisterDTO getRegisterdto() {
		return registerdto;
	}

	public void setRegisterdto(RegisterDTO registerdto) {
		this.registerdto = registerdto;
	}


	
}
